package com.lili.collection.core.utils;

import com.lili.collection.core.domain.CollectCommonConfig;
import com.lili.collection.core.domain.NoticeConfig;
import com.lili.collection.core.fields.Field;
import com.lili.collection.core.handler.ICallBackHandler;
import com.lili.collection.core.handler.ISendMsg;
import com.lili.collection.core.processor.JSONFlatProcessor;
import com.lili.collection.core.processor.JSONUnFlatProcessor;
import com.lili.collection.core.record.Record;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *描述: 通知工具
 *@date: 2023/12/22  11:32
 *@author: lili
 */
@Slf4j
public class NoticeUtil {

    /**
     * 发送数据和存储通知报文
     * @param config 配置
     * @param output 输出数据
     */
    public static void saveNotice(CollectCommonConfig config, List<Record> output,String successed){
        NoticeConfig noticeConfig = config.getNoticeConfig();
        if(noticeConfig==null || !noticeConfig.isEnable() || CollectionUtils.isEmpty(output)){
            return;
        }
        ICallBackHandler callBackHandler = config.getCallBackHandler();
        if(callBackHandler==null){
            throw new IllegalArgumentException("通知回调函数为空！");
        }
        String nowTime = DateConvertUtil.getNowStr();
        for (Record record : output) {
            try {
                Map<String, Field> row = record.getField().getValueAsMap();
                JSONObject jsonObject = new JSONObject(row.size());
                for (String fieldName : row.keySet()) {
                    jsonObject.put(fieldName, row.get(fieldName).getValue());
                }
                JSONFlatProcessor processor = new JSONFlatProcessor();
                processor.setConfigMap(noticeConfig.getNoticeAliasMap());
                processor.process(jsonObject);
                List<Map<String, Object>> dataList = processor.getDataWithMap();
                if(CollectionUtils.isEmpty(dataList)){
                    throw new IllegalArgumentException("当前映射【"+noticeConfig.getNoticeAliasMap()+"】的结果：【"+jsonObject+"】存在空值   DB通知映射数据不能为空！");
                }
                noticeHandler(noticeConfig, callBackHandler, dataList,nowTime,successed);
            } catch (Throwable throwable) {
                log.error("json转换异常!", throwable);
                throw throwable;
            } 
        }
    }

    /**
     * 发送数据和存储通知报文
     * @param config 配置
     * @param data 数据
     * @param sendMsg 消息发送公用方法
     */
    public static boolean sendDataAndSaveNotice(CollectCommonConfig config, String data, ISendMsg sendMsg) throws Exception{
        NoticeConfig noticeConfig = config.getNoticeConfig();
        if(noticeConfig==null || !noticeConfig.isEnable()){
            return sendMsg.sendProducer(data);
        }
        ICallBackHandler callBackHandler = config.getCallBackHandler();
        if(callBackHandler==null){
            throw new IllegalArgumentException("通知回调函数为空！");
        }
        JSONFlatProcessor processor = new JSONFlatProcessor();
        processor.setConfigMap(noticeConfig.getNoticeAliasMap());
        processor.process(data);
        List<Map<String, Object>> dataList = processor.getDataWithMap();
        if(CollectionUtils.isEmpty(dataList)){
            throw new IllegalArgumentException("通知映射数据不能为空！");
        }
        String nowTime = DateConvertUtil.getNowStr();
        Throwable throwable=null;
        String successed="Y";
        try {
            if(!sendMsg.sendProducer(data)){
                throw new IllegalStateException("采集输出失败！");
            }
        } catch (Throwable e) {
            throwable=e;
            successed="N";
        }
        noticeHandler(noticeConfig, callBackHandler, dataList, nowTime, successed);
        if(throwable!=null){
            throw new IllegalArgumentException(throwable);
        }
        return true;
    }

    private static void noticeHandler(NoticeConfig noticeConfig, ICallBackHandler callBackHandler,
                                      List<Map<String, Object>> dataList, String nowTime, String successed) {

        Map<String, String> noticeAliasMap = getNoticeAliasMap(noticeConfig, dataList);
        for (Map<String, Object> objectMap : dataList) {
            //需要获取映射路径
            if(StringUtils.isNotBlank(noticeConfig.getSjczbzPath())){
                objectMap.put(noticeConfig.getSjczbzPath(), successed);
            }
            if(StringUtils.isNotBlank(noticeConfig.getSjczsjPath())){
                objectMap.put(noticeConfig.getSjczsjPath(), nowTime);
            }
            JSONUnFlatProcessor unProcessor=new JSONUnFlatProcessor();
            unProcessor.parseSingleMap(objectMap);
            String notice = unProcessor.toString();
            noticeConfig.setSendTime(nowTime);
            callBackHandler.onHandler(notice, noticeConfig,noticeAliasMap);
        }
    }

    private static Map<String,String> getNoticeAliasMap(NoticeConfig noticeConfig, List<Map<String, Object>> dataList) {
        Map<String, Object> noticeMap = dataList.get(0);
        Map<String,String> noticeAliasMap = new HashMap<>();
        for (String targetName : noticeMap.keySet()) {
            noticeAliasMap.put(JsonPathAnalysisUtil.getRealPathByTarget(targetName),targetName);
        }
        String flag = noticeConfig.getSjczbzPath();
        if(StringUtils.isNotBlank(flag)){
            noticeAliasMap.put(JsonPathAnalysisUtil.getRealPathByTarget(flag),  flag);
        }
        String time= noticeConfig.getSjczsjPath();
        if(StringUtils.isNotBlank(time)){
            noticeAliasMap.put(JsonPathAnalysisUtil.getRealPathByTarget(time), time);
        }
        return noticeAliasMap;
    }
}